<template>
    <div>
        <yh-dialog
            :visible.sync="dialogVO.visible"
            :title="dialogVO.title"
            width="600px"
            drag
            :close-on-click-modal="false"
            :close-on-press-escape="false"
        >
            <div class="set-border">
                <div>
                    <el-button type="primary" @click="putDictfile" style="margin-right:8px">选择文件</el-button>
                    <input type="file" ref="putInput" style="display: none" @change="putDictfiles" />
                    <el-button type="primary" @click="downLoadTemplate"> 导入模板下载</el-button>
                </div>
                <div class="radio-content">
                    <div>
                        <el-radio v-model="importType" label="1"><span class="set-bold">替换文件导入</span></el-radio>
                        <span class="set-block">
                            注：替换界面中目前已存在的明细信息
                        </span>
                    </div>
                    <div>
                        <el-radio v-model="importType" label="2"><span class="set-bold">追加方式导入</span></el-radio>
                        <span class="set-block">注：导入界面目前不存在的明细信息</span>
                    </div>
                </div>
            </div>
            <span class="set-block set-bold"> 导入总数量： {{ resultInfo.totalNum }} </span>
            <span class="set-block set-bold"> 导入成功数量：{{ resultInfo.successNum }} </span>
            <span class="set-block set-bold"> 导入失败数量：{{ resultInfo.errorNum }} </span>
            <el-button type="primary" @click="downLoadError" :disabled="!resultInfo.errorNum">
                导入失败明细下载
            </el-button>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="cancel"> 取 消 </el-button>
                <el-button size="mini" type="primary" @click="confirm"> 确 定 </el-button>
            </div>
        </yh-dialog>
    </div>
</template>
<script lang="ts">
import { downLoadFile } from '@/utils/request';
import { getUser } from '@/utils/user-util';
import { DialogVO } from '@yhfin/biz';
import axios from 'axios';
import { Component, Prop, Vue } from 'vue-property-decorator';
import * as XLSX from 'xlsx';

@Component({
    name: 'LoadIn',
    components: {},
})
export default class LoadIn extends Vue {
    @Prop() dialogVO: DialogVO;
    importType: string = '1';
    @Prop() currentData: any;
    private fileNames: string = ''; // 上传文件名
    private putTableDataList: any[] = []; // 导入表数据
    resultInfo = {
        errorExcelPath: '',
        errorNum: 0,
        successNum: 0,
        totalNum: 0,
    };

    // 导入模板下载
    downLoadTemplate() {
        // let url = '/componyPool/import/template/' + this.currentData.issueGroupCategory;
        // let blob = new Blob([url], {
        //     type: 'application/vnd.ms-excel',
        // });
        // let requestUrl = URL.createObjectURL(blob);
        // let link = document.createElement('a');
        // let fileName = '模板' + '.xlsx';
        // document.body.appendChild(link);
        // link.href = requestUrl;
        // link.download = fileName;
        // link.click();
        // link.remove();
        downLoadFile({
            url: '/componyPool/import/template/' + this.currentData.issueGroupCategory,
            method: 'post',
            data: {},
        });
    }

    // 导入失败明细下载
    downLoadError() {
        downLoadFile({
            url: '/componyPool/down/errorExcel',
            method: 'post',
            data: {
                downFileName: this.resultInfo.errorExcelPath,
            },
        });
    }

    // 选取文件
    private putDictfiles(e) {
        let files = e.currentTarget.files;
        const formData = new FormData();
        formData.append('file', files[0]);
        new Promise((resolve, reject) => {
            let reader = new FileReader();
            if (!files || files.length === 0) {
                // eslint-disable-next-line prefer-promise-reject-errors
                reject();
            }
            reader.readAsBinaryString(files[0]);

            reader.onload = e => {
                let webBook = XLSX.read(e.target.result, { type: 'binary' });
                let data = [];
                for (let sheet in webBook.Sheets) {
                    if (webBook.Sheets.hasOwnProperty(sheet)) {
                        data = data.concat(XLSX.utils.sheet_to_json(webBook.Sheets[sheet]));
                        break;
                    }
                }
                resolve(data);
            };
            reader.onerror = error => {
                reject(error);
            };
        }).then((res: any) => {
            this.$axios
                .post(
                    '/componyPool/import/relationData?category=' +
                        this.currentData.issueGroupCategory +
                        '&groupCode=' +
                        this.currentData.id +
                        '&importType=' +
                        this.importType,
                    formData,
                    {
                        headers: { 'Content-Type': 'multipart/form-data' },
                    }
                )
                .then((res: any) => {
                    this.resultInfo = res;
                    if (this.resultInfo.errorNum > 0) {
                        this.yh_message_error(`${this.resultInfo.errorNum}条数据导入失败,可点击下方导出错误原因`);
                    } else {
                        this.yh_message_success('导入成功');
                    }
                })
                .catch(() => {
                    this.yh_message_error('导入失败');
                });
            // try {
            //     let entryDetails = [];
            //     entryDetails = res
            //         .map(item => {
            //             return {
            //                 issueCode: Object.values(item)[0],
            //                 issueName: Object.values(item)[1],
            //                 issueNameSt: Object.values(item)[2],
            //                 key: Object.values(item)[0],
            //             };
            //         })
            //         .filter(item => !!item.issueCode);
            //     if (entryDetails.length === 0) {
            //         this.yh_message_error('数据格式不正确或者数据为空，导入失败');
            //         return;
            //     }
            //     this.putTableDataList = entryDetails;
            //     this.fileNames = files[0].name;
            // } catch (e) {
            //     this.yh_message_error('数据格式不正确，导入失败');
            // }
        });
    }
    // 选择文件
    private putDictfile(): void {
        (this.$refs['putInput'] as any).value = null;
        (this.$refs['putInput'] as any).click();
    }

    // '确认'导入
    private loadinDetailDialogConfirm(): void {
        let entryDetails = this.putTableDataList;
        if (!entryDetails || entryDetails.length === 0) {
            this.yh_message_warn('请选择需要上传的条目文件');
            return;
        }
        let formFile = new FormData();

        axios({
            method: 'post',
            url: '/componyPool/import/relationData',
            baseURL: '',
            responseType: 'blob',
            data: {
                category: this.currentData.issueGroupCategory,
                groupCode: this.currentData.id,
                importType: this.importType,
                file: formFile,
            },
            headers: { Authentication: getUser().sessionId },
        })
            // this.$axios
            //     .post('/componyPool/import/relationData', {
            //         category: this.currentData.issueGroupCategory,
            //         groupCode: this.currentData.id,
            //         importType: this.importType,
            //     })
            .then((res: any) => {
                this.$emit('load-return', 'confirm');
            })
            .catch(err => {
                console.log(err, 'err');
            });
    }

    cancel() {
        this.$emit('load-return', 'cancel');
    }

    confirm() {
        this.$emit('load-return', 'confirm');
    }
}
</script>
<style lang="scss" scoped>
.radio-content {
    margin-top: 16px;
    display: flex;
    justify-content: space-between;
}
.set-bold {
    font-weight: bolder;
}
.set-block {
    display: block;
    font-size: 14px;
    margin: 10px 0;
}
.set-border {
    border: 1px solid #cccc;
    padding: 10px 5px;
    margin-bottom: 8px;
}
</style>
